// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package list

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib"
)

// Logic
// 渔票分页.
type Logic struct {
	arcade   *models.Arcades
	admin    *models.ArcadeAdmins
	request  *Request
	response []*Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: make([]*Response, 0),
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.arcade, _ = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		conditions = map[string]any{"arcade_id": o.arcade.Id}
		err        error
		list       []*models.Ticket
		pid        = make([]int64, 0)
		res        = result.New()
		total      int64
	)

	// 1. 状态过滤.
	if o.request.State > 0 {
		conditions["state"] = o.request.State
	}

	// 2. 读取列表.
	if list, total, err = services.NewTicketService().Paging(ctx, conditions, o.request.Page, o.request.Size); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2.1 遍历列表.
	for _, item := range list {
		if item.PondId > 0 {
			pid = append(pid, item.PondId)
		}
		o.response = append(o.response, (&Response{}).With(item))
	}

	// 2.2 绑定鱼塘.
	if len(pid) > 0 {
		var mapper map[int64]*models.ArcadePond

		if mapper, err = services.NewArcadePondService().MapByIdList(ctx, pid); err != nil {
			return res.WithError(errs.ErrDatabaseQuery)
		}

		for _, item := range o.response {
			if pond, ok := mapper[item.PondId]; ok {
				item.WithPond(pond)
			}
		}
	}

	// 3. 加载完成.
	return res.WithPaging(o.response, total, o.request.Page, o.request.Size)
}
